import http from 'wechat-http'
// 添加基地址
http.baseURL = 'https://live-api.itheima.net'
http.intercept.request = function (options) {
  // 扩展头信息
  const defaultHeader = {}
   // 读取 token
  const  token  = getApp().token
  // 追加 token 头信息
  if (token) defaultHeader.Authorization = token
    
  // 与默认头信息合并
  options.header = Object.assign({}, defaultHeader, options.header)
  // 处理后的请求参数
  return options
}
// 响应拦截器配置
http.intercept.response = async (res) => {
  if(res.data.code == 401) {
    if(res.config.url.includes('/refreshToken')) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
      return
    }
    const app = getApp()
    const res1 = await http({
      url:'/refreshToken',
      method:'POST',
      header:{
        Authorization:app.refreshToken
      }
    })
    getApp().setToken(res1.data.token,res1.data.refreshToken)
    http(Object.assign(res.config,{header:{Authorization:getApp().token}}))
  }
  return res.data
}
// 导出方法
wx.http = http
export default http